<template>

    <div class="app-container">

    <el-card shadow='never'>
      <div class="btn_wrapper">
        <span style="font-size: 12px; color: pink;">说明：目前支持学科和关键字条件筛选</span>
        <el-button type="success" class="btn-success" @click="$router.push({path:'/questions/new'})">
          <i class="el-icon-edit"></i>
          <span>新增试题</span>
        </el-button>
      </div>
      <!-- 此处是11个表单内容 -->

        <el-form ref="form" :model="ruleForm" class="el-form" label-width="80px" size="mini">
          <el-form-item label="学科" class="el-form-item" prop="subjectID">
             <el-select class="el-select" v-model="ruleForm.subjectID" @change="allList">
                  <el-option v-for="item in subjectList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="二级目录" class="el-form-item" prop="catalogID">
             <el-select class="el-select" v-model="ruleForm.catalogID" >
                  <el-option v-for="item in Second_directory"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
             </el-select>
          </el-form-item>
           <el-form-item label="标签" class="el-form-item" prop="tags">
             <el-select class="el-select" v-model="ruleForm.tags" >
                  <el-option v-for="item in tags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="关键字" class="el-form-item" prop="keyword">
             <el-input class="el-input"  v-model="ruleForm.keyword"></el-input>
          </el-form-item>
           <el-form-item label="试题类型" class="el-form-item" prop="questionType">
              <el-select class="el-select" v-model="ruleForm.questionType" >
                  <el-option v-for="item in question_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="难度" class="el-form-item" prop="difficulty">
             <el-select class="el-select" v-model="ruleForm.difficulty">
               <el-option v-for="item in difficulty_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
             </el-select>
          </el-form-item>
            <el-form-item label="方向" class="el-form-item" prop="direction">
              <el-select class="el-select" v-model="ruleForm.direction">
               <el-option v-for="item in direction_type"
                  :key="item.index"
                  :label="item"
                  :value="item"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="录入人" class="el-form-item" prop="creatorID">
              <el-select class="el-select" v-model="ruleForm.creatorID">
               <el-option v-for="item in usersname"
                  :key="item.id"
                  :label="item.username"
                  :value="item.username"></el-option>
             </el-select>
          </el-form-item>
           <el-form-item label="题目备注" class="el-form-item" prop="remarks">
            <el-input class="el-input" v-model="ruleForm.remarks"></el-input>
          </el-form-item>
           <el-form-item label="企业简称" class="el-form-item" prop="shortName">
            <el-input class="el-input" v-model="ruleForm.shortName"></el-input>
          </el-form-item>
           <el-form-item label="城市" class="el-form-item" prop="province">
            <el-select class="el-select" v-model="ruleForm.province" @change="citysFn" style="width:48%; margin-right:2%;">
               <el-option v-for="item in provinceslist"
                  :key="item.index"
                  :label="item"
                  :value="item"></el-option>
             </el-select>
              <el-select class="el-select" v-model="ruleForm.city" style="width:50%; ">
               <el-option v-for="item in citylist"
                  :key="item.index"
                  :label="item"
                  :value="item"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="" class="el-form-item items" style="text-align: right;" prop="button">
             <el-button class="el-button" @click="resetForm">清除</el-button>
             <el-button class="el-button" type="primary" @click.prevent="look">搜索</el-button>
          </el-form-item>
        </el-form>

      <!-- 此处是切换栏 -->
      <el-col :span="24">
         <el-tabs class="el-tabs" type="card" @tab-click="handleClick" >
              <el-tab-pane label="全部" name="0"></el-tab-pane>
              <el-tab-pane label="待审核" name="1"></el-tab-pane>
              <el-tab-pane label="已审核" name="2"></el-tab-pane>
              <el-tab-pane label="已拒绝" name="3"></el-tab-pane>
            </el-tabs>
      </el-col>

      <!-- 此处是提示框 -->
        <el-alert
          class="el-alert"
          :title="`数据一共${total}条`"
          type="info"
          show-icon
          :closable='false'>

        </el-alert>
      <!--此处是表格  -->
         <el-table
          :data="list"
          style="width: 100%"
          >
        <el-table-column
            prop="number"
            label="试题编号"
            width="150">
        </el-table-column>

          <el-table-column
            prop="subject"
            label="学科"
            width="120">
          </el-table-column>

          <el-table-column
            prop="catalog"
            label="目录"
            width="120">
          </el-table-column>

          <el-table-column
            prop="questionType"
            label="题型"
            width="120">
            <template #default="{row}">
              {{ questionTypelist(row.questionType) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="question"
            label="题干"
            width="300">
            <template #default="{row}">
              {{ questionpParse(row.question) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="addDate"
            label="录入时间"
            width="150">
             <template #default="{row}">
              {{ formateTimeFn(row.addDate) }}
            </template>
          </el-table-column>

           <el-table-column
            prop="difficulty"
            label="难度"
            width="120">
            <template #default="{row}">
              {{ difficultyFn(row.difficulty) }}
            </template>
          </el-table-column>

           <el-table-column
            prop="creator"
            label="录入人"
            width="120">
          </el-table-column>

           <el-table-column
            prop="chkState"
            label="审核状态"
            width="120">
            <template #default="{row}">
              {{ chkTypefn(row.chkState) }}
            </template>
          </el-table-column>

           <el-table-column
            prop="chkRemarks"
            label="审核意见"
            width="120">
          </el-table-column>

          <el-table-column
            prop="chkUser"
            label="审核人"
            width="120">
          </el-table-column>

          <el-table-column
            prop="publishState"
            label="发布状态"
            width="120">
            <template #default="{row}">
              {{ publishTypefn(row) }}
            </template>
          </el-table-column>

          <el-table-column
            fixed='right'
            prop="zip"
            label="操作"
            width="200"
            align="center">
            <template #default="{row}">
              <el-button @click="previewClick(row)" type="text" size="small">预览</el-button>
              <el-button type="text" size="small" :disabled="cstate(row)" @click="opendialog(row)">审核</el-button>
              <el-button type="text" size="small" :disabled="cchange(row)" @click="$router.push({path:`/questions/new?id=${row.id}`})">修改</el-button>
              <el-button type="text" size="small"  @click="openConfirm(row)" ref="confirm" >{{(row.publishState === 1 )? '下架':'上架'}}</el-button>
              <el-button type="text" size="small" :disabled="delConfirm(row)" @click="delfn(row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!-- 此处是分页 -->
    <div class="block" style="margin-top: 20px; text-align: right;">

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-size="pagesize"
      :page-sizes="[5, 10, 20, 50]"
      layout=" prev, pager, next, sizes,jumper"
      background
      :total="total">
    </el-pagination>
    </div>
    <!-- 此处是审核弹出框 -->
        <el-dialog title="题目审核" :visible.sync="dialogcheck" style="width: 800px; border-radius: 10px
            position: relative;
            margin: 0 auto;">
              <el-form ref="checkForm" :model="checkForm" :rules="rules" style="display: block;">
                <el-form-item label="" prop="chkState">
                      <el-radio-group v-model="checkForm.chkState" style="display: block; width:720px;" >
                        <el-radio label=1>通过</el-radio>
                        <el-radio label=2>拒绝</el-radio>
                      </el-radio-group>
                </el-form-item>

                <el-form-item label="" prop="chkRemarks" style="display: block; width:360px; margin-bottom:10px;"  >
                  <el-input  v-model="checkForm.chkRemarks"  placeholder="请输入审核意见" type="textarea"></el-input>
                </el-form-item>
                </el-form>
              <div slot="footer" class="dialog-footer" style="display: block;margin-top:80px; text-align: right;">

                <el-button @click="dialogcheck = false">取 消</el-button>
                <el-button type="primary" @click="checkFn()" >确认</el-button>

              </div>
        </el-dialog>
    <!-- 此处是预览弹出框 -->
          <el-dialog title="题目预览" :visible.sync="dialogPreview" style="width: 1800px; border-radius: 10px;">
            <div>
              <span >【题型】：{{ questionTypelist(previewlist.questionType) }}题</span>
              <span style="margin-left:120px">【编号】：{{previewlist.id}}</span>
              <span style="margin-left:120px">【难度】：{{difficultyFn(previewlist.difficulty) }}</span>
              <span style="margin-left:120px">【标签】：{{previewlist.tags}}</span>
            </div>
            <div style="margin-top:30px">
              <span >【学科】：{{previewlist.subjectName}}</span>
              <span style="margin-left:120px">【目录】：{{previewlist.directoryName}}</span>
              <span style="margin-left:120px">【方向】：{{previewlist.direction}}</span>
            </div>
            <hr style="margin-top:20px">
            <div>
              <span >【题干】：</span>
            </div>
            <div class="one" style="color: blue;">

               <p v-html="previewlist.question"></p>
            </div>
            <div style="margin-top: 20px">
              <p>{{ questionTypelist(previewlist.questionType) }}题 选项：（以下选中的选项为正确答案）</p>
            </div>
            <div style="margin-top: 20px" v-if=" +previewlist.questionType=== 1||2 ">
              <el-radio-group v-model="radiolist" size="small" >
                <el-radio :label="item.isRight" @change="kfcFn" style="display:block;margin-top: 20px"
                v-for="item in previewlist.options"

                :key="item.id"
                :value="item.isRight">{{item.title}}</el-radio>
                <!-- <el-radio  style="display:block;margin-top: 20px">{{previewlist.options[0].title}}</el-radio>
                <el-radio  style="display:block;margin-top: 20px">{{previewlist.options[1].title}}</el-radio>
                <el-radio  style="display:block;margin-top: 20px">{{previewlist.options[2].title}}</el-radio>
                <el-radio  style="display:block;margin-top: 20px">{{previewlist.options[3].title}}</el-radio> -->
              </el-radio-group>
            </div>
            <hr style="margin-top: 10px">
            <div>
              <span>【参考答案】：</span>
              <el-button type="danger" @click="SeeVideo">
              视频答案预览  </el-button>

                 <video
                 style="display:block"
                 v-show="viewVideo"
                  :src="this.videoUrl"
                  width="500"
                  controls="controls"
                  :state="viewVideo"
                  ref="vueRef"
                  ></video>

            </div>
            <hr style="margin-top: 10px">
            <div>
              <span>【答案解析】：</span>
              <span v-html="previewlist.answer" style="display:inline-block;"></span>
            </div>
             <hr style="margin-top: 10px">
            <div>
              <span>【题目备注】：</span>
              <span>{{previewlist.remarks}}</span>
            </div>
            <div style="margin-top: 100px;text-align: right;">
              <el-button style="" type="primary" @click="dialogPreview=false">关闭</el-button>
            </div>
          </el-dialog>

    </el-card>
    </div>

</template>

<script>

import { simple } from '@/api/hmmm/subjects'
import { simple as Simple } from '@/api/hmmm/directorys'
import { simple as simpleTags } from '@/api/hmmm/tags'
import { questionType, difficulty, direction, chkType, publishType, status } from '@/api/hmmm/constants'
import { simple as userSimple } from '@/api/base/users'
import { choice, choiceCheck, choicePublish, remove, detail } from '@/api/hmmm/questions'
import dayjs from 'dayjs'
import { provinces, citys } from '@/api/hmmm/citys'

export default {
  name: 'questions-choice',
  data () {
    return {
      ruleForm: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''

      },
      checkForm: {
        chkState: 0,
        chkRemarks: ''
      },
      rules: {
        chkState: [{ required: true, message: '用户名不可为空', trigger: 'blur' }],
        chkRemarks: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }]
      },

      subjectList: [],
      Second_directory: [],
      tags: [],
      keyword: '',
      question_type: [...questionType],
      difficulty_type: [...difficulty],
      direction_type: [...direction],
      usersname: [],
      Topic_desc: '',
      company_desc: '',
      provinceslist: [],
      citylist: [],
      page: 1,
      pagesize: 5,
      list: [],
      total: 0,
      addDate: '',
      chkTypelist: [...chkType],
      publishTypelist: [...publishType],
      dialogcheck: false,
      dialogUP: true,
      status,
      dialogPreview: false,
      radiolist: 1,
      previewlist: {},
      checklist: {},
      // 弹窗展示状态 默认false
      viewVideo: false,
      // 视频链接   这个大家可以写上自己的视频地址
      videoUrl: 'https://mo-1314261685.cos.ap-beijing.myqcloud.com/TUOER.mp4'
    }
  },
  created () {
    this.List()
    this.userSimplelist()
    // 列表数据
    this.choiceList()
    this.mapList()
  },
  methods: {
    kfcFn () {
      this.radiolist = 1
    },
    /**
     * 获取一级目录
     */
    async List () {
      const { data } = await simple()
      this.subjectList = data
    },
    /**
     * 获取二级目录
     */
    async simpleList (id) {
      const { data } = await Simple({ subjectID: id })
      this.Second_directory = data
    },
    /**
     * 获取标签
     */
    async simpleTagslist (id) {
      const { data } = await simpleTags({ subjectID: id })
      this.tags = data
    },
    /**
     * 一级目录改变时执行
     */
    allList (id) {
      this.simpleList(id)
      this.simpleTagslist(id)
    },
    /**
     * 录入人的列表
     */
    async userSimplelist () {
      const { data } = await userSimple()
      this.usersname = data
    },
    /**
     * 获取省
     */
    mapList () {
      this.provinceslist = provinces()
    },
    /**
     * 获取市
     */
    citysFn (val) {
      this.citylist = citys(val)
    },
    /**
     * 重置表单
     */
    resetForm () {
      this.$refs.form.resetFields()
      this.ruleForm = {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      }
      // 重新渲染
      this.choiceList()
    },
    /**
     * 搜索按钮
     */
    async look () {
      // 进行if判断当前处于全部状态还是搜索状态
      // 学科筛选
      const isRfc = this.list.every(item => item.subjectID === this.ruleForm.subjectID)
      // 关键字和题干对比筛选
      // .split('')字符串转换为字符数组
      const isRfs = this.list.every(item => (this.questionpParse(item.question).split('')).includes(this.ruleForm.keyword))
      if (isRfc || isRfs) {
        // 走搜索状态下的搜索
        // 以下是搜索功能
        const newForm = {}
        for (const key in this.ruleForm) {
        // console.log(this.ruleForm[key])
          if (this.ruleForm[key]) {
          // console.log(111)
            newForm[key] = this.ruleForm[key]
          }
        }
        const { data } = await choice({
        // subjectID: this.ruleForm.subjectID || '',
        // keyword: this.ruleForm.keyword || '',
          ...newForm,
          page: this.page,
          pagesize: this.pagesize
        })
        // 重新渲染列表
        this.total = data.counts
        this.list = data.items
        this.page = +data.page
        this.pagesize = +data.pagesize
      } else {
        // 走全部状态下搜索
        // 以下是搜索功能
        const newForm = {}
        for (const key in this.ruleForm) {
        // console.log(this.ruleForm[key])
          if (this.ruleForm[key]) {
          // console.log(111)
            newForm[key] = this.ruleForm[key]
          }
        }
        const { data } = await choice({
        // subjectID: this.ruleForm.subjectID || '',
        // keyword: this.ruleForm.keyword || '',
          ...newForm,
          page: 1,
          pagesize: this.pagesize
        })
        // 重新渲染列表
        this.total = data.counts
        this.list = data.items
        this.page = +data.page
        this.pagesize = +data.pagesize
      }
    },
    /**
     * 获取题目详情列表(核心)
     */
    async choiceList () {
      const { data: { items, counts } } = await choice({ page: this.page, pagesize: this.pagesize })
      this.list = items
      this.total = counts
      // console.log(items, counts)
    },
    /**
     * 点击页码时触发
     *每一页的题目数量
     */
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      // 学科筛选
      const isRfc = this.list.every(item => item.subjectID === this.ruleForm.subjectID)
      // 关键字和题干对比筛选
      // .split('')字符串转换为字符数组
      const isRfs = this.list.every(item => (this.questionpParse(item.question).split('')).includes(this.ruleForm.keyword))
      if (isRfc || isRfs) {
        this.look(this.page)
      } else {
        this.choiceList()
      }
      // this.choiceList()
      // this.look()
    },
    /**
     * 点击页码时触发
     * val 点击的那个页码
     */
    handleCurrentChange (val) {
      // console.log(this.list)

      this.page = val
      // 学科筛选
      const isRfc = this.list.every(item => item.subjectID === this.ruleForm.subjectID)
      // 关键字和题干对比筛选
      // .split('')字符串转换为字符数组
      const isRfs = this.list.every(item => (this.questionpParse(item.question).split('')).includes(this.ruleForm.keyword))
      console.log(isRfs)
      console.log(isRfc)
      if (isRfc || isRfs) {
        this.look()
      } else {
        this.choiceList()
      }
    },
    /**
     * 选出题目类型
     */
    questionTypelist (res) {
      return this.question_type.find(item => +res === item.value)?.label
    },
    /**
     * 解析标签文本内容
     */
    questionpParse (val) {
      return val.replace(/<[^>]+>/g, '')
    },
    /**
     * 格式化时间
     */
    formateTimeFn (time) {
      // 处理成 年-月-日 并且返回
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    /**
     * 难度枚举选择
     */
    difficultyFn (val) {
      return this.difficulty_type.find(item => +val === item.value)?.label
    },
    /**
     * 录入状态枚举选择
     */
    chkTypefn (val) {
      return this.chkTypelist.find(item => +val === item.value)?.label
    },
    /**
     * 发布状态
     */
    publishTypefn (row) {
      if (row.publishState === 1 && row.chkState === 1) { return '已发布' }
      if (row.publishState === 0 && row.chkState === 1) { return '已下架' }
      return '待发布'
      // return this.publishTypelist.find(item => +val === item.value)?.label
    },
    /**
     * 审核表单提交
     */
    async checkFn () {
      // 统一校验
      this.$refs.checkForm.validate(async flag => {
        if (!flag) return
        await choiceCheck({
          id: this.checklist.id,
          chkState: +this.checkForm.chkState,
          chkRemarks: this.checkForm.chkRemarks
        })
        this.$message.success('操作成功!')
        this.dialogcheck = false
        this.choiceList()
      })

      // await choiceCheck({
      //   id: this.checklist.id,
      //   chkState: +this.checkForm.chkState,
      //   chkRemarks: this.checkForm.chkRemarks
      // })
      // this.dialogcheck = false
      // this.choiceList()
    },
    /**
     * 打开检查框
     */
    opendialog (row) {
      this.dialogcheck = true
      this.checklist = row
    },
    /**
     * 上架下架提示框
     */
    openConfirm (row) {
      if (row.publishState === 1) {
        this.$confirm('您确认下架这道题目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.$message({
            type: 'success',
            message: '下架成功!'
          })
          // this.$nextTick( () => {
          await choicePublish({ id: row.id, publishState: +!row.publishState })
          // })

          this.choiceList()
        }).catch(() => {
          console.log('出错了')
        })
      } else {
        this.$confirm('您确认上架这道题目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.$message({
            type: 'success',
            message: '上架成功!'
          })
          // this.$nextTick( () => {
          await choicePublish({ id: row.id, publishState: +!row.publishState })

          this.choiceList()
        }).catch(() => {
          console.log('出错了')
        })
      }
    },
    /**
     * 判断审核状态
     */
    cstate (row) {
      if (row.chkState === 0) { return false }
      if (row.chkState === 1 || row.chkState === 2) { return true }
    },
    /**
     * 判断修改是否高亮
     */
    cchange (row) {
      // console.log(111)
      if (row.publishState === 1 && row.chkState === 1) { return true }
      if (row.publishState === 0 && row.chkState === 1) { return false }
      return false
    },
    /**
     *删除是否高亮
     */
    delConfirm (row) {
      if (row.publishState === 1 && row.chkState === 1) { return true } else {
        return false
      }
    },
    /**
     * 删除id操作
     */
    delfn (row) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await remove(row)
        this.choiceList()
      }).catch(() => {
        console.log('出错了')
      })
    },
    /**
     * tab切换操作
     */

    async handleClick (val) {
      // console.log(val._props.name)
      const newForm = {}
      for (const key in this.ruleForm) {
        // console.log(this.ruleForm[key])
        if (this.ruleForm[key]) {
          // console.log(111)
          newForm[key] = this.ruleForm[key]
        }
      }
      if (val._props.name === '0') {
        const { data } = await choice({ ...newForm, page: this.page, pagesize: this.pagesize })
        // 重新渲染列表
        this.total = data.counts
        this.list = data.items
        this.page = +data.page
        this.pagesize = +data.pagesize
      } else {
        const { data } = await choice({ ...newForm, page: this.page, pagesize: this.pagesize, chkState: +val._props.name - 1 })
        // 重新渲染列表
        this.total = data.counts
        this.list = data.items
        this.page = +data.page
        this.pagesize = +data.pagesize
      }
    },
    /**
     * 预览按钮
     */
    async previewClick (row) {
      this.dialogPreview = true
      const { data } = await detail(row)
      // console.log(data)
      this.previewlist = { ...data }
    },
    /**
     * 预览题目详情
     */
    async detailfn (row) {
      await detail()
    },
    // 预览视频
    SeeVideo () {
      this.viewVideo = !this.viewVideo
      // this.$refs.vueRef.play()// 播放
    },

    // 取消预览
    handleCancel (e) {
      this.viewVideo = false
      this.$refs.vueRef.pause()// 暂停
    }

  },
  computed: {

  },
  watch: {
    list: {
      handler (newv, oldv) {
        // console.log(newv)
        this.list = newv
      }
    }

  }
}
</script>

<style scoped lang='scss' >
.app-container{
  border-radius: 4px;
    padding: 0 10px;
    margin: 10px 0;
//头部
.btn_wrapper{
margin-bottom: 15px;
display: flex;
-webkit-box-pack: justify;
justify-content: space-between;
.btn-success{
    color: #fff;
    background-color: #67c23a;
    border-color: #67c23a;
        font-size: 12px;
    border-radius: 3px;
    padding: 9px 15px;
}
}
//表单
.el-form{
    display: block;
    margin-top: 0em;
    box-sizing: border-box;
    .el-form-item{
      width: 25%;
      float: left;
      box-sizing: border-box;
      margin-bottom: 18px;
      line-height: 32px;

    .el-select {
    display: inline-block;
    position: relative;
    width: 100%;

                  }
    .el-input{

    font-size: 13px;
    position: relative;
    display: inline-block;
    width: 100%;
    }
    .el-button{

      padding: 9px 15px;
      display: inline-block;

    }

    }

}
//切换栏
.el-tabs{
display: block;
color: #303133;

}
.el-alert{
margin-bottom: 15px;
}

}

</style>
